package eip.chapter4.guaranteed.util;

import java.io.StringReader;
import java.io.StringWriter;

import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.JiBXException;

import eip.chapter4.guaranteed.GroceryOrder;

public class JiBXHelper {

	private static IBindingFactory orderFactory;
	
	private static IBindingFactory getFactory() throws JiBXException {
		if(orderFactory == null) {
			orderFactory = BindingDirectory.getFactory(GroceryOrder.class);
		}
		return orderFactory;
	}
	
	public static String createOrderinXML(GroceryOrder order) throws JiBXException {
		StringWriter writer = new StringWriter();
		getFactory().createMarshallingContext().marshalDocument(order, "UTF-8", null, writer);
		return writer.toString();
	}
	
	public static GroceryOrder createOrderFromXML(String orderMessage) throws JiBXException {
		return (GroceryOrder) getFactory().createUnmarshallingContext().
				unmarshalDocument(new StringReader(orderMessage), null);
	}
}
